package com.dt.app.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dt.app.common.response.ResultUtil;
import com.dt.app.exception.CmsCodeException;
import com.dt.app.exception.CmsPasswordException;
import com.dt.app.exception.CmsTokenException;
import com.dt.app.exception.ExcelException;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


/**
 * 登录认证失败处理器
 * @author DT
 * @date 2021/6/5 10:31
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = httpServletResponse.getOutputStream();
        String msg;
        int code = 5000;
        if(e instanceof AccountExpiredException) {
            msg = "账号过期，登录失败!";
        } else if(e instanceof DisabledException) {
            msg = "账号被禁用，登录失败!";
        } else if(e instanceof LockedException) {
            msg = "账号被锁，登录失败!";
        } else if(e instanceof UsernameNotFoundException) {
            msg = "账号不存在，登录失败!";
        } else if(e instanceof BadCredentialsException) {
            msg = "密码错误，登录失败!";
        } else if(e instanceof CredentialsExpiredException) {
            msg = "证书过期，登录失败!";
        } else if(e instanceof SessionAuthenticationException) {
            msg = "您当前账号，已在另一台设备登录!";
        } else if(e instanceof CmsPasswordException) {
            msg = e.getMessage();
        } else if(e instanceof ExcelException) {
            msg = e.getMessage();
        } else if(e instanceof CmsTokenException) {
            // token验证异常
            code = 6000;
            msg = e.getMessage();
        } else if(e instanceof CmsCodeException) {
            code = 6001;
            msg = e.getMessage();
        } else{
            msg = "登录失败!";
        }
        String res = JSONObject.toJSONString(ResultUtil.error(code,msg), SerializerFeature.DisableCircularReferenceDetect);
        out.write(res.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
